package com.example.a2032.activity;

import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.Space;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.example.a2032.R;
import com.example.a2032.Utils.BleSdk;
import com.example.a2032.Utils.Utils;
import com.example.a2032.Utils.WebSocketUtils;
import com.example.a2032.entity.PPGMeasureData;
import com.example.a2032.net.jstylenet.JstyleConst;
import com.example.a2032.net.jstylenet.NetSendUtils;

import java.util.concurrent.TimeUnit;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import io.reactivex.Observer;
import io.reactivex.disposables.Disposable;

public class Spo2MeasureActivity extends BaseActivity {


    @BindView(R.id.iv_meausre_ready)
    ImageView ivMeausreReady;
    @BindView(R.id.tv_measure_tips1)
    TextView tvMeasureTips1;
    @BindView(R.id.tv_measure_tips2)
    TextView tvMeasureTips2;
    @BindView(R.id.iv_spo2_result)
    ImageView ivSpo2Result;
    @BindView(R.id.ivSpo2)
    ImageView ivSpo2;
    @BindView(R.id.tvSpo2Value)
    TextView tvSpo2Value;
    @BindView(R.id.ivSpo2Hr)
    ImageView ivSpo2Hr;
    @BindView(R.id.tvSpo2HrValue)
    TextView tvSpo2HrValue;
    @BindView(R.id.tv_spo2Unit)
    TextView tvSpo2Unit;
    @BindView(R.id.tv_spo2HrUnit)
    TextView tvSpo2HrUnit;
    @BindView(R.id.space)
    Space space;
    @BindView(R.id.iv_spo2Alert)
    ImageView ivSpo2Alert;
    @BindView(R.id.tv_spo2ResultAlert)
    TextView tvSpo2ErrorResultAlert;
    @BindView(R.id.tv_spo2ResultTips)
    TextView tvSpo2ErrorResultTips;
    @BindView(R.id.tv_ReMeasure)
    TextView tvReMeasure;
    @BindView(R.id.iv_spo2_measureGif)
    ImageView ivSpo2MeasureGif;
     int maxMeasureTime;
    Disposable disposableMeasureTimer;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        KeepScreenOn();
        setContentView(R.layout.activity_spo2_measure);
        ButterKnife.bind(this);
        init();
    }

    long startMeasureTime;
    String from = "";

    private void init() {
        from = getIntent().getStringExtra(KEY_MeasureFrom);
        maxMeasureTime=getIntent().getIntExtra(KEY_MeasureTime,2);
        //服务器端传过来的时间可能是0
        if(maxMeasureTime==0)maxMeasureTime=2;
        subscribe(this);
        sendData(BleSdk.enableSpo2Measure(true,maxMeasureTime));
        startMeasureTime = System.currentTimeMillis();
        showMeasureView(true);
        Glide.with(this).asGif().load(R.mipmap.measure_spo).into(ivSpo2MeasureGif);
        Utils.startMeasureTimer(maxMeasureTime, new Observer() {
            @Override
            public void onSubscribe(Disposable d) {
                disposableMeasureTimer=d;
            }

            @Override
            public void onNext(Object o) {

            }

            @Override
            public void onError(Throwable e) {

            }

            @Override
            public void onComplete() {
                    finish();
            }
        });
//        tvMeasureTips1.postDelayed(new Runnable() {
//            @Override
//            public void run() {
//                showErrorResultViews();
//            }
//        },6000);
    }
    private Disposable disposableFinish;
    void showResultViews() {
        ivSpo2Result.setVisibility(View.VISIBLE);
    }
    void startFinishTimer() {
        Utils.startMeasureTimer(5, TimeUnit.SECONDS, new Observer() {
            @Override
            public void onSubscribe(Disposable d) {
                disposableFinish = d;
            }

            @Override
            public void onNext(Object o) {

            }

            @Override
            public void onError(Throwable e) {

            }

            @Override
            public void onComplete() {
                finish();
            }
        });
    }

    void showErrorResultViews() {
        ivSpo2MeasureGif.setVisibility(View.GONE);
        ivSpo2Result.setVisibility(View.GONE);
        space.setVisibility(View.VISIBLE);
        ivSpo2Alert.setVisibility(View.VISIBLE);
        tvSpo2ErrorResultAlert.setVisibility(View.VISIBLE);
        tvSpo2ErrorResultTips.setVisibility(View.VISIBLE);
        tvReMeasure.setVisibility(View.VISIBLE);
    }

    void showMeasureValue(PPGMeasureData ppgMeasureData) {
        int hrValue = ppgMeasureData.getHeartRate();
        int spo2Value = ppgMeasureData.getMeasureValue();
        tvSpo2Value.setText(String.valueOf(spo2Value + "%"));
        tvSpo2HrValue.setText(String.valueOf(hrValue));
        if (spo2Value == 0 || hrValue == 0) {

        } else {
            sendData(BleSdk.enableSpo2Measure(false));
            Utils.startVibrato(this);
            showMeasureView(false);
            upLoadData(spo2Value, JstyleConst.Measure_Finish);
            isMeasureFinish=true;
            Utils.saveBPData(this,ppgMeasureData,from);
            if (spo2Value < 95) {
                showErrorResultViews();
            } else {
                startFinishTimer();
                showResultViews();
            }
        }

    }

    void upLoadData(int spo2Value, int state) {
        String msg = NetSendUtils.realTimeSpo2Data(spo2Value, state, from);
        WebSocketUtils.getInstance().sendMsg(msg);
    }

    private static final String TAG = "Spo2MeasureActivity";

    @OnClick({R.id.tv_ReMeasure})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.tv_ReMeasure:
                reMeasure();
                break;
        }
    }

    /**
     * 显示正在测量的view
     *
     * @param isMeasure
     */
    private void showMeasureView(boolean isMeasure) {
        showWearTipsView(isMeasure);
        ivSpo2.setVisibility(isMeasure ? View.INVISIBLE : View.VISIBLE);
        tvSpo2Value.setVisibility(isMeasure ? View.INVISIBLE : View.VISIBLE);
        tvSpo2Unit.setVisibility(isMeasure ? View.INVISIBLE : View.VISIBLE);
        ivSpo2Hr.setVisibility(isMeasure ? View.GONE : View.VISIBLE);
        tvSpo2HrValue.setVisibility(isMeasure ? View.GONE : View.VISIBLE);
        tvSpo2HrUnit.setVisibility(isMeasure ? View.GONE : View.VISIBLE);

    }

    private void showWearTipsView(boolean show) {
        ivMeausreReady.setVisibility(show ? View.VISIBLE : View.GONE);
        tvMeasureTips1.setVisibility(View.GONE );
        tvMeasureTips2.setText(getString(R.string.measure_tips2));
        tvMeasureTips2.setVisibility(show ? View.VISIBLE : View.GONE);
    }

    //测试异常后重新测量
    private void reMeasure() {
        isMeasureFinish=false;
        ivSpo2Alert.setVisibility(View.GONE);
        tvSpo2ErrorResultAlert.setVisibility(View.GONE);
        tvSpo2ErrorResultTips.setVisibility(View.GONE);
        tvReMeasure.setVisibility(View.GONE);
        showMeasureView(true);

    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        unSubscribe(disposableMeasureTimer);
        unSubscribe(disposableFinish);
        sendData(BleSdk.enableSpo2Measure(false));
        KeepScreenOff();
        if(!isMeasureFinish) upLoadData(0, JstyleConst.Measure_Finish);
    }
    boolean isWearOff=false;
    boolean isMeasureFinish;
    @Override
    public void PPGMeasureData(PPGMeasureData ppgMeasureData) {
        super.PPGMeasureData(ppgMeasureData);
        int type = ppgMeasureData.getDataType();
        if (type == PPGMeasureData.MeasureData_PPGSPO2) {
            int wearStatus = ppgMeasureData.getWearStatus();
            if (wearStatus == PPGMeasureData.MeasureStatus_WearOff) {
                isWearOff=true;
                ivMeausreReady.setVisibility(View.VISIBLE);
                ivSpo2MeasureGif.setVisibility(View.GONE);
                ivSpo2Result.setVisibility(View.GONE);
                tvMeasureTips2.setText(getString(R.string.measure_tips2));
                tvMeasureTips1.setVisibility(View.GONE );
                upLoadData(0, JstyleConst.Measure_WearOff);
            } else {
                isWearOff=false;
                if (System.currentTimeMillis() - startMeasureTime > 6000) {
                    ivMeausreReady.setVisibility(View.INVISIBLE);
                    ivSpo2MeasureGif.setVisibility(View.VISIBLE);
                    ivSpo2Result.setVisibility(View.VISIBLE);
                    tvMeasureTips1.setVisibility(View.VISIBLE );
                    tvMeasureTips2.setText("");
                }
            }
            Log.i(TAG, "PPGMeasureData: " + wearStatus);
            showMeasureValue(ppgMeasureData);
        }
    }

    @Override
    protected void stopMeasure() {
        super.stopMeasure();
        finish();
    }
}